
export function debounce(fn, wait) {
  var timer = null;
  return function () {
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(fn, wait);
  };
}

export function onMonacoResize(vnode, fn, wait = 700) {
  if (!(vnode && vnode.$el && vnode.$once)) {
    throw new Error("vnode not a vue instance");
  }
  const observer = new ResizeObserver(
    typeof wait === 'number' && wait > 0
      ? debounce(fn, wait)
      : fn
  );
  observer.observe(vnode.$el, { box: "border-box" });
  return vnode.$once("hook:beforeDestory", () => observer.disconnect());
}

const baseUrl = location.href.includes("/qryFramework/")
  ? location.href.split("/qryFramework/").shift()
  : location.origin

const monacoUri = 'monaco-editor@0.38.0';
/** 初始化创建AMD-loader */
function initAMDLoader() {
  return new Promise((resolve) => {
    const { require } = window;
    if (typeof require == "function" && typeof require.define == "function") {
      return resolve(require);
    }
    let scriptElement = document.querySelector("script#monaco-editor-loader");
    if (!scriptElement) {
      scriptElement = document.createElement("script");
      scriptElement.setAttribute("id", "monaco-editor-loader");
      scriptElement.setAttribute("src", `${monacoUri}/loader.js`);
      document.querySelector("head").append(scriptElement);
    }
    scriptElement.addEventListener("load", () => resolve(window.require));
  });
}

self.MonacoEnvironment = {
  getWorkerUrl(workerId, label, ...args) {
    if (label == "json") {
      return `${baseUrl}/${monacoUri}/worker/json.worker.js`;
    }
    if (label == "javascript" || label == "typescript") {
      return `${baseUrl}/${monacoUri}/worker/ts.worer.js`;
    }
    return `${baseUrl}/${monacoUri}/worker/editor.worker.js`;
  },
};

export async function getMonaco(...languages) {
  return loadMonaco("vs/editor/editor.main", ...languages).then(([monaco]) => monaco);
}

export function loadMonaco(...names) {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve) => {
    const load = await initAMDLoader();
    load.config({
      paths: {
        vs: "monaco-editor@0.38.0/vs",
      },
      "vs/nls": { availableLanguages: { "*": "zh-cn" } },
    });
    load(["vs/editor/editor.main"], () => {
      load(names, (...mods) => resolve(mods));
    });
  });
}
